<?php


namespace app\finance\controller;


use app\base\BaseController;
use think\Exception;
use think\facade\Db;
use think\facade\View;

class SaleReceipt extends BaseController
{
protected $title='销售收款单';
protected $table='money_order';
protected $mType=1;

    public function index()
    {
        $param=$this->request->param();
        if (request()->isAjax()) {
            $where[]=['mo.status','>',-1];
            $where[]=['mo.type','=',$this->mType];

            if (isset($this->param['status'])&&$this->param['status']){
                $where[]=['mo.status','=',$this->param['status']];
            }
            if (isset($this->param['name'])&&$this->param['name']){
                $where[]=['py.name|py.code|ad.name|mo.orderNum','like','%'.$this->param['name'].'%'];
            }
            if (isset($this->param['orderDate'])&&$this->param['orderDate']){
                $dates=explode('~',$this->param['orderDate']);
                $where[]=['mo.orderDate','between',$dates];
            }
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name($this->table)
                ->alias('mo')
                ->leftJoin('purveyor py','py.id=mo.purveyorId')
                ->leftJoin('admin ad','ad.id=mo.checkId')
                ->where($where)
                ->field('mo.*,py.name as pName,ad.name as payName')
                ->order('mo.id DESC')
                ->paginate($rows);
            return table_assign(0, '', $list);
        } else {
            return view();
        }
    }

    public function add()
    {
        $param=$this->param;
        $id=$param['id']??0;
        if ($this->request->post()){
//            if (!$param['purveyorId']||!$param['contractOrder']){
            if (!$param['purveyorId']){
                return  to_assign(1,'参数缺失');
            }
            $param['update_time'] = time();

            try {
                if ($id){
                    Db::name($this->table)->save($param);
                    add_log('edit', $id, $this->param,$this->title);

                }else{
                    unset($param['id']);
                    $param['createId']=$this->uid;
                    $param['orderNum']=dJBHBySql($this->table,'orderNum','SKD'.date('Ymd'),false,1000);
                    $param['type']=$this->mType;
                    $param['departId']=$this->did;
                    $param['create_time'] = time();
                    $param['contactMoney'] = $param['contactMoney']??0;
                    $id=Db::name($this->table)->insertGetId($param);
                    add_log('add', $id, $this->param,$this->title);
                }

            }catch (\Exception $e){
                return to_assign(1,'操作失败：'.$e->getMessage());
            }
            return  to_assign();

        }else{
            $punList=Db::name('purveyor')->where('status',1)->where('dw_type',2)->field('id,name')->select();
            $detail=[];
            if ($id){
                $detail=Db::name($this->table)->where('id',$id)->find();
            }
            View::assign('punList',$punList);
            View::assign('detail',$detail);
            View::assign('id',$id);
            return view('form');
        }
    }

    public function delete()
    {
        $ids=$this->param['id']??[];
        if (!$ids){
            return to_assign(1,'参数缺失');
        }
        $status=Db::name($this->table)->where('id','in',$ids)->column('status');
        if (in_array(2,$status)){
            return to_assign(1,'参数有误');
        }
        Db::startTrans();
        try {
            Db::name($this->table)->where('id','in',$ids)->update(['status'=>-1,'deleted'=>time()]);
          Db::name('money_order_contract_detail')
                ->where('status','=',1)
                ->where('orderId','in',$ids)->update(['status'=>-1,'deleted'=>time()]);
            add_log('delete', $ids, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }

        return to_assign();
    }

    public function onSure()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $info=Db::name($this->table)->where('id',$id)->find();
        if (!$info||$info['status']!=1){
            return to_assign(1,'参数有误');
        }


        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'checkTime'=>date('Y-m-d H:i:s'),
                'status'=>2,
                'update_time'=>time()]);

            $money_order_contract_detail=Db::name('money_order_contract_detail')
                ->where('status','=',1)
                ->where('orderId',$id)
                ->select();
            foreach ($money_order_contract_detail as $v){
                $conTractInfo=Db::name('sale_contract')
                    ->where('orderNum',$v['contractOrder'])
                    ->where('status',4)
                    ->field("*,(select sum(money) from fy_money_order_contract_detail mo where mo.status=2 and mo.contractOrder=fy_sale_contract.orderNum)receiptedMoney")
                    ->find();

                if ($conTractInfo){
                    $conTractInfo['receiptedMoney']=$conTractInfo['receiptedMoney']?$conTractInfo['receiptedMoney']:0;
                    $conTractInfo['unPay']=$conTractInfo['countMoney']-$conTractInfo['receiptedMoney'];
                    if ($conTractInfo['unPay']<$v['money']){
                        throw new Exception('金额大于合同金额');
                    }
                    if ($conTractInfo['unPay']==$v['money']){
                        Db::name('sale_contract')->where('id',$conTractInfo['id'])
                            ->update(['payStatus'=>3,'update_time'=>time(),'payOverTime'=>date('Y-m-d H:i:s')]);
                    }
                    if ($conTractInfo['unPay']>$v['money']){
                        Db::name('sale_contract')->where('id',$conTractInfo['id'])
                            ->update(['payStatus'=>2,'update_time'=>time()]);
                    }

                }
            }
            if ($money_order_contract_detail){
                $recordData=[
                    'orderDate'=>$info['orderDate'],
                    'relatedOrderNum'=>$info['orderNum'],
                    'purveyorId'=>$info['purveyorId'],
                    'money'=>$info['money'],
                    'orderType'=>$this->mType,

                ];
                moneyRecord($recordData);
            }
            Db::name('money_order_contract_detail')
                ->where('status','=',1)
                ->where('orderId',$id)->update(['status'=>2]);
            add_log('onSure', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }

    public function htdk()
    {
        $param=$this->param;
        $receiptId=$param['receiptId'];
        $info=Db::name($this->table)->where('id',$receiptId)->find();
        if ($this->request->post()){
            if (!$info){
                return to_assign(1,'参数有误');
            }
            $data=$param['data']??[];
            if (empty($data)){
                return to_assign(1,'参数缺失');
            }
            $ids=[];
            Db::startTrans();
            try {
                $countMoney=Db::name('money_order_contract_detail')
                    ->where('orderId',$receiptId)->where('status','>',-1)
                    ->where('status','=',2)
                    ->sum('money');

                foreach ($data as $v){
                    $countMoney+=$v['money'];
                }
                if ($countMoney>$info['money']){
                    throw new Exception('合计金额大于收款金额');
                }
                foreach ($data as $v){

                $insData=[
                    'purveyorId'=>$v['punterId'],
                    'money'=>$v['money'],
                    'orderId'=>$receiptId,
                    'contactMoney'=>$v['countMoney'],
                    'contractOrder'=>$v['orderNum'],
                    'type'=>$this->mType,
                    'createId'=>$this->uid,
                    'status'=>$info['status']==1?1:2,
                    'departId'=>$this->did,
                    'create_time'=>time(),
                    'update_time'=>time(),

                ];
                    $ids[]=Db::name('money_order_contract_detail')->insertGetId($insData);
                    if ($info['status']==2){
                        $saleContractMony=Db::name('sale_contract')->where('orderNum',$v['orderNum'])->value('countMoney');
                        $payedMoney=Db::name('money_order_contract_detail')
                            ->where('status','=',2)
                            ->where('contractOrder',$v['orderNum'])->sum('money');
                        if ($payedMoney>=$saleContractMony){
                            $updata=[
                                'payStatus'=>3
                            ];
                        }else{
                            $updata=[
                                'payStatus'=>2
                            ];
                        }
                        $updata['update_time']=time();
                        Db::name('sale_contract')->where('orderNum',$v['orderNum'])
                            ->update($updata);
                    }

            }
                Db::name($this->table)->where('id',$receiptId)->update(['contactMoney'=>$countMoney]);
                add_log('htdk', implode(',',$ids), $this->param,$this->title);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
                return to_assign(1,'操作失败:'.$e->getMessage());
            }
            return to_assign();

        }else{
            $purveyorId=$info['purveyorId']??0;
            view::assign('receiptId',$receiptId);
            view::assign('purveyorId',$purveyorId);
            view::assign('info',$info);
            return view();
        }
    }

    public function dkMx()
    {
        $param=$this->request->param();
        $receiptId=$param['receiptId'];
        if ($this->request->isAjax()){
            $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
            $list = Db::name('money_order_contract_detail')
                ->alias('mocd')
                ->leftJoin('admin a','a.id=mocd.createId')
                ->where('mocd.status','>',-1)
                ->where('mocd.orderId',$receiptId)
                ->field('mocd.*,a.username')
                ->paginate($rows)->each(function ($item){
                    $item['create_time']=date('Y-m-d H:i:s',$item['create_time']);
                    return $item;
                });

            return table_assign(0,'',$list);

        }else{
            view::assign('receiptId',$receiptId);
            return view('');
        }
    }

    public function onCancel()
    {
        $id=$this->param['id']??0;
        if (!$id){
            return to_assign(1,'参数缺失');
        }
        $info=Db::name($this->table)->where('id',$id)->find();
        if (!$info||$info['status']!=2){
            return to_assign(1,'参数有误');
        }


        Db::startTrans();
        try {
            Db::name($this->table)->where('id',$id)->update([
                'checkId'=>$this->uid,
                'checkTime'=>date('Y-m-d H:i:s'),
                'status'=>1,
                'update_time'=>time()]);

            $money_order_contract_detail=Db::name('money_order_contract_detail')
                ->where('status','=',2)
                ->where('orderId',$id)
                ->select();
            foreach ($money_order_contract_detail as $v){
                $conTractInfo=Db::name('sale_contract')
                    ->where('orderNum',$v['contractOrder'])
                    ->where('status',4)
                    ->field("*,(select sum(money) from fy_money_order_contract_detail mo where mo.status=2 and mo.contractOrder=fy_sale_contract.orderNum)receiptedMoney")
                    ->find();

                if ($conTractInfo){
                    $conTractInfo['receiptedMoney']=$conTractInfo['receiptedMoney']?$conTractInfo['receiptedMoney']:0;
                    $conTractInfo['unPay']=$conTractInfo['countMoney']-$conTractInfo['receiptedMoney']+$v['money'];
//                    if ($conTractInfo['unPay']<$v['money']){
//                        throw new Exception('金额大于合同金额');
//                    }

                    if ($conTractInfo['unPay']==$conTractInfo['countMoney']){
                        Db::name('sale_contract')->where('id',$conTractInfo['id'])
                            ->update(['payStatus'=>1,'update_time'=>time(),'payOverTime'=>date('Y-m-d H:i:s')]);
                    }
                    if ($conTractInfo['unPay']<$conTractInfo['countMoney']){
                        Db::name('sale_contract')->where('id',$conTractInfo['id'])
                            ->update(['payStatus'=>2,'update_time'=>time(),'payOverTime'=>date('Y-m-d H:i:s')]);
                    }

                }
            }
            Db::name('money_order_contract_detail')->where('status',2)
                ->where('orderId',$id)
                ->update(['status'=>-1,'update_time'=>time(),'deleted'=>time()]);
            if ($money_order_contract_detail){
                $recordData=[
                    'orderDate'=>$info['orderDate'],
                    'relatedOrderNum'=>$info['orderNum'],
                    'purveyorId'=>$info['purveyorId'],
                    'money'=>$info['money'],
                    'orderType'=>$this->mType,

                ];
                moneyRecord($recordData);
            }
            Db::name('money_order_contract_detail')
                ->where('status','=',1)
                ->where('orderId',$id)->update(['status'=>2]);
            add_log('onSure', $id, $this->param,$this->title);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            return to_assign(1,'操作失败:'.$e->getMessage());
        }
        return to_assign(0,'操作成功');
    }
}